import React, { Component } from 'react';
import {
  Row,
  Col,
  Card,
  List,
  Avatar,
  Button,
  Form,
  Popconfirm,
  Divider,
  Input,
  Modal,
  Slider,
  InputNumber,
  Collapse,
  Icon,
  message,
  Select,
  Radio,
} from 'antd';
import Link from 'umi/link';
import { formatMessage } from 'umi/locale';
import { connect } from 'dva';
import OrderForm from './hdForms/OrderForm';
import ThicknessMaxForm from './hdForms/ThicknessMaxForm';
import { Stage, Layer, Text, Image, Line, Label, Tag, Rect } from 'react-konva';
import AgvArgsForm from './hdForms/AgvArgsForm';

@connect(({ produce }) => ({ produce }))
class BoardImageShow extends React.Component {
  constructor(props) {
    super(props);
  }
  state = {
    image: null,
  };
  componentDidMount() {
    this._isMounted = true;
    const image = new window.Image();
    image.src = this.props.produce.boardImageSrc;
    image.onload = () => {
      if (this._isMounted) {
        this.setState({
          image: image,
        });
      }
    };
  }

  componentWillUpdate() {
    const image = new window.Image();
    image.src = this.props.produce.boardImageSrc;
    image.onload = () => {
      this.setState({
        image: image,
      });
    };
  }

  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }

  render() {
    return (
      <Image
        image={this.state.image}
        width={this.state.image ? this.state.image.width : 500}
        height={this.state.image ? this.state.image.height : 500}
      />
    );
  }
}

@connect(({ produce, hd, os, ds }) => ({ produce, hd, os, ds }))
@Form.create()
class Produce extends Component {
  state = {
    search_orderId: '',
    flatBoardMax: 0,
    btnClickFlag: true,
    thicknessSetVal: 0,
    chooseToWhereModalVislbe: false,
    radioValue: 1, // 默认是选择收料平台1.
  };

  // 小车作业去向切换
  onRadioChage = e => {
    this.setState({
      radioValue: e.target.value,
    });
  };

  // 关闭设备启动提示框
  closeProduceStartModal = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'produce/closeProduceStartModal',
    });
  };

  closeAlarmModal = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'produce/closeTipsModal',
    });
  };
  clear_grate_alarm = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'produce/clearGrateAlarm',
    });
  };

  // 点击历史数据的时候
  clickHistory = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'os/clickHistory',
    });
  };

  onChange = (key, e) => {
    console.log(key, e.props.children);
    this.setState({
      search_orderId: e.props.children,
    });
  };

  // 选择小车的作业去向
  chooseToWhere = e => {
    const { dispatch } = this.props;
    this.setState({
      chooseToWhereModalVislbe: true,
    });
  };

  clickStartProduce = e => {
    const { dispatch } = this.props;
    const { btnStartClicked } = this.props.produce;
    const { workingOrder } = this.props.os;
    const { radioValue } = this.state;

    if (btnStartClicked) {
      // 按钮已经点击过了,就什么也不做.
    } else {
      // 如果是第一次点击,就执行自动作业的流程
      dispatch({
        type: 'produce/updateStartProduceBtn',
        payload: true,
      });
      dispatch({
        type: 'produce/clickStartProduce',
        payload: [workingOrder[0], radioValue],
      });
    }
  };

  // 点击搜索
  clickSearch = e => {
    console.log('search');
    const { dispatch } = this.props;
    const { search_orderId } = this.state;
    dispatch({
      type: 'os/searchOrder',
      payload: search_orderId,
    });
  };

  // 点击搜索之后的返回
  clickBack = e => {
    console.log('back');
    const { dispatch } = this.props;
    dispatch({
      type: 'hd/getServerOrder',
    });
  };

  clickReset = e => {
    console.log('reset');
    const { dispatch } = this.props;
    const { btnResetAllClicked } = this.props.produce;
    dispatch({
      type: 'produce/updateResetAllBtnClick',
      payload: true,
    });
    if (btnResetAllClicked) {
      // 如果按钮被按下就什么都不做
    } else {
      dispatch({
        type: 'produce/clickResetAll',
      });
    }
  };
  ExcepReset = e => {
    console.log('Excep');
    const { dispatch } = this.props;
    dispatch({
      type: 'ds/ExcepReset',
    });
  };
  clickExcepReset = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ds/clickExcepReset',
    });
  };
  clickStopProduce = e => {
    console.log('stop');
    const { dispatch } = this.props;
    dispatch({
      type: 'produce/updateBoardImageModalState',
      payload: [false, null, '无提示消息,作业未开始!'],
    });
    dispatch({
      type: 'produce/clickStopProduce',
    });
  };

  closeModal = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'hd/closeModal',
    });
  };
  handleQuit = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'hd/stop_auto',
    });
    this.closeModal();
    dispatch({
      type: 'produce/stop',
    });
  };
  // 界面上点击了自动作业弹出来的小车作业去向
  clickChooseToWhere = e => {
    this.setState({
      chooseToWhereModalVislbe: false,
    });
    this.clickStartProduce(); // 调用自动作业的逻辑.
  };

  // 切换放板位置
  changePutBoardPos = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ds/changePutBoardPos',
    });
  };

  jackingUpStateLV01 = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ds/jackingUpStateLV01',
    });
  };
  clearLv1FullQuit = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'produce/clearLv1FullQuit',
    });
  };

  jackingUpStateLV02 = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ds/jackingUpStateLV02',
    });
  };
  clearLv2FullQuit = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'produce/clearLv2FullQuit',
    });
  };
  clearPinFlag = e => {
    const { dispatch } = this.props;
    const { pinFlag } = this.props.ds;
    dispatch({
      type: 'produce/clearPinFlag',
      payload: pinFlag,
    });
  };
  closeRaster = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'produce/closeRaster',
    });
  };
  openRaster = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'produce/openRaster',
    });
  };
  setAGVOrArtificial = e => {
    const { dispatch } = this.props;
    const { BMSR } = this.props.ds;
    dispatch({
      type: 'produce/setAGVOrArtificial',
      payload: BMSR,
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const {
      autoEnable,
      runStateCam,
      errorMsg,
      rsStateCam,
      carType,
      errorInfo, // 控制器和相机拍摄异常的提示信息
      errorInfoModalVisble, // 底层的弹窗是否显示
      produceStartModalVisible, // 设备启动提示框
      produceStartModalInfo, // 设置提示框的内容
      boardImageVisible, // 识别的提示的图
      boardImageSrc, // 识别异的图片
      boardImageInfo, // 识别提示信息
      resetModalVisible, // 复位提示框
      resetModalInfo, // 复位提示信息
      btnResetAllClicked, // 复位按钮被按下
    } = this.props.produce;
    const { btnName, btnClickFlag, chooseToWhereModalVislbe, radioValue } = this.state;

    const {
      mainZmcStates, // 主控制器状态
      camZmcStates, // 分流机控制器状态
      mainAlarmInfo, // 主控制器报警状态
      mainAlarmInfoVisible, // 主控制报警状态是否显示
      cameraGroupStates, // 相机组状态
      autoState, // 是否是自动作业状态
      grateHidded, // 门报警是否屏蔽
      grateClear, // 门报警清除
      doorAlarm, // 门报警
      putBoardPos, // 放板位置.
      boardThicknessMax, // 叠板厚度
      agvArgsData, // AGV参数
      fullStateLV01, // LV01是否满的状态
      fullStateLV02, // LV02是否满的状态
      pinFlag,
      changeLv1Button,
      changeLv2Button,
      BMSR,
      infoStartAGV,
    } = this.props.ds;

    const { totalOrders, workingOrder } = this.props.os; // 工单数据
    const gridStyle = {
      width: '40%',
      textAlign: 'left',
    };
    const gridStyle2 = {
      width: '40%',
      textAlign: 'left',
    };
    const gridStyle3 = {
      width: '60%',
      textAlign: 'left',
    };

    const { Option } = Select;
    const children = [];
    for (let i = 0; i < totalOrders.length; i++) {
      children.push(<Option key={i.toString() + i}>{totalOrders[i]['cutId']}</Option>);
    }
    return (
      <>
        <Card>
          <Card.Grid style={{ width: '50%', textAlign: 'left' }}>
            <span>
              <font style={{ color: '#0000FF', fontSize: 19 }}>收板机状态</font>
            </span>
            <span style={{ marginLeft: 20 }}>
              连接:&nbsp;&nbsp;&nbsp;
              {mainZmcStates.online ? (
                <font style={{ color: '#00FF00', fontSize: 16 }}>已连接</font>
              ) : (
                <font style={{ color: '#FF0000', fontSize: 16 }}>已断开</font>
              )}{' '}
            </span>
            <span style={{ marginLeft: 10 }}>
              状态:&nbsp;&nbsp;&nbsp;{' '}
              {mainZmcStates.rs ? (
                <font style={{ color: '#FF0000', fontSize: 16 }}>急停中</font>
              ) : mainZmcStates.run ? (
                <font style={{ color: '#00FF00', fontSize: 16 }}>运行中</font>
              ) : (
                <font style={{ color: '#112233', fontSize: 16 }}>待机</font>
              )}
            </span>
            <span>
              <font style={{ color: '#0000FF', fontSize: 19, marginLeft: 10 }}>分流机状态</font>
            </span>
            <span style={{ marginLeft: 20 }}>
              连接:&nbsp;&nbsp;&nbsp;
              {camZmcStates.online ? (
                <font style={{ color: '#00FF00', fontSize: 16 }}>已连接</font>
              ) : (
                <font style={{ color: '#FF0000', fontSize: 16 }}>已断开</font>
              )}{' '}
            </span>
            <span style={{ marginLeft: 10 }}>
              状态:&nbsp;&nbsp;&nbsp;{' '}
              {camZmcStates.rs ? (
                <font style={{ color: '#FF0000', fontSize: 16 }}>急停中</font>
              ) : camZmcStates.run ? (
                <font style={{ color: '#00FF00', fontSize: 16 }}>运行中</font>
              ) : (
                <font style={{ color: '#112233', fontSize: 16 }}>待机</font>
              )}
            </span>
            <span style={{ marginLeft: 30 }}>
              相机1:&nbsp;&nbsp;&nbsp;
              {cameraGroupStates[0] ? (
                <font style={{ color: '#00FF00', fontSize: 16 }}>已连接</font>
              ) : (
                <font style={{ color: '#FF0000', fontSize: 16 }}>已断开</font>
              )}
            </span>
            <span style={{ marginLeft: 30 }}>
              相机2:&nbsp;&nbsp;&nbsp;
              {cameraGroupStates[1] ? (
                <font style={{ color: '#00FF00', fontSize: 16 }}>已连接</font>
              ) : (
                <font style={{ color: '#FF0000', fontSize: 16 }}>已断开</font>
              )}
            </span>
          </Card.Grid>
          <Card.Grid style={{ width: '50%', textAlign: 'left' }}>
            <span>
              {' '}
              <font style={{ color: '#0000FF', fontSize: 16 }}>当前放板位置:</font>
            </span>
            <span style={{ marginLeft: 20 }}>
              <font style={{ color: '#FF00FF', fontSize: 19 }}>{putBoardPos}</font>
            </span>
            <Button
              style={{ height: '100%', width: 150, marginLeft: 20, textAlign: 'center' }}
              type="primary"
              onClick={this.changePutBoardPos}
            >
              切换放板位置
            </Button>
            <span style={{ marginLeft: 20 }}>
              {' '}
              <font style={{ color: '#0000FF', fontSize: 16 }}>下料状态:</font>
            </span>
            {BMSR ? (
              <font style={{ color: '#00FF00', fontSize: 16 }}>AGV模式</font>
            ) : (
              <font style={{ color: '#FF00FF', fontSize: 16 }}>人工模式</font>
            )}
            {BMSR ? (
              <Button style={{ marginLeft: 40 }} onClick={this.setAGVOrArtificial}>
                AGV模式
              </Button>
            ) : (
              <Button style={{ marginLeft: 20 }} onClick={this.setAGVOrArtificial}>
                人工模式
              </Button>
            )}
            <p>
              {' '}
              <font style={{ color: '#0000FF', fontSize: 16 }}>:{infoStartAGV}</font>
            </p>
          </Card.Grid>
        </Card>
        <Card>
          <Card.Grid style={{ width: '50%' }}>
            <Stage width={510} height={510}>
              <Layer>{boardImageSrc ? <BoardImageShow /> : <Image width={500} />}</Layer>
            </Stage>
            <p>{<font style={{ color: '#FF0000', fontSize: 16 }}>提示消息: </font>}</p>
            <p>
              <font style={{ color: '#FF0000', fontSize: 20 }}>{boardImageInfo}</font>
            </p>
          </Card.Grid>
          <Card.Grid style={{ width: '50%', textAlign: 'left' }}>
            <Card title="自动作业">
              <Row style={{ marginTop: 10, marginLeft: 20, marginBottom: 10 }}>
                <Button
                  id="btnClickAuto"
                  onClick={this.chooseToWhere}
                  disabled={autoState || mainZmcStates.rs || mainZmcStates.run}
                >
                  开始
                </Button>
                <Button
                  style={{ marginLeft: 30 }}
                  onClick={this.clickStopProduce}
                  disabled={!autoState && !mainZmcStates.run}
                >
                  停止
                </Button>
                <Button style={{ marginLeft: 30 }} onClick={this.clickReset} disabled={autoState}>
                  复位
                </Button>
              </Row>
            </Card>
            <Card title="设置叠板厚度" style={{ marginTop: 30 }}>
              <ThicknessMaxForm order={boardThicknessMax} />
            </Card>
            <Card title="AGV参数设置" style={{ marginTop: 30 }}>
              <AgvArgsForm agvArgsData={agvArgsData} />
            </Card>
            <Card title="载料台操作" style={{ marginTop: 10 }}>
              <Row style={{ marginTop: 10, textAlign: 'left' }}>
                <span>
                  {
                    <font style={{ color: '#0000FF', fontSize: 16, marginLeft: 20 }}>
                      收料平台1状态:{' '}
                    </font>
                  }
                </span>
                {fullStateLV01 == '已放满' ? (
                  <span>
                    {
                      <font style={{ color: '#FF0000', fontSize: 20, marginLeft: 20 }}>
                        {fullStateLV01}{' '}
                      </font>
                    }
                  </span>
                ) : (
                  <span>
                    {
                      <font style={{ color: '#000000', fontSize: 16, marginLeft: 20 }}>
                        {fullStateLV01}{' '}
                      </font>
                    }
                  </span>
                )}
                {changeLv1Button ? (
                  <Button
                    style={{ marginLeft: 20 }}
                    onClick={this.jackingUpStateLV01}
                    disabled={BMSR}
                  >
                    收料平台1启动
                  </Button>
                ) : (
                  <Button style={{ marginLeft: 20 }} onClick={this.clearLv1FullQuit}>
                    取出收料平台1
                  </Button>
                )}
              </Row>
              <Row style={{ marginTop: 20, textAlign: 'left', marginBottom: 10 }}>
                <span>
                  {
                    <font style={{ color: '#0000FF', fontSize: 16, marginLeft: 20 }}>
                      收料平台2状态:{' '}
                    </font>
                  }
                </span>
                {fullStateLV02 == '已放满' ? (
                  <span>
                    {
                      <font style={{ color: '#FF0000', fontSize: 20, marginLeft: 20 }}>
                        {fullStateLV02}{' '}
                      </font>
                    }
                  </span>
                ) : (
                  <span>
                    {
                      <font style={{ color: '#000000', fontSize: 16, marginLeft: 20 }}>
                        {fullStateLV02}{' '}
                      </font>
                    }
                  </span>
                )}
                {changeLv2Button ? (
                  <Button
                    style={{ marginLeft: 20 }}
                    onClick={this.jackingUpStateLV02}
                    disabled={BMSR}
                  >
                    收料平台2启动
                  </Button>
                ) : (
                  <Button style={{ marginLeft: 20 }} onClick={this.clearLv2FullQuit}>
                    取出收料平台2
                  </Button>
                )}
              </Row>
              <Row>
                {pinFlag ? (
                  <Button
                    style={{ marginLeft: 20, color: '#00FF00' }}
                    onClick={this.clearPinFlag}
                    disabled={autoState}
                    size="large"
                  >
                    正常放板
                  </Button>
                ) : (
                  <Button
                    style={{ marginLeft: 20, color: '#FF0000' }}
                    onClick={this.clearPinFlag}
                    disabled={autoState}
                    size="large"
                  >
                    旋转放板
                  </Button>
                )}
                <Button style={{ marginLeft: 20 }} onClick={this.closeRaster} size="large">
                  光栅屏蔽
                </Button>
                <Button style={{ marginLeft: 20 }} onClick={this.openRaster} size="large">
                  光栅启动
                </Button>
              </Row>
            </Card>
          </Card.Grid>
        </Card>
        <Card title="设置物料参数" size="small">
          <div style={{ marginBottom: 5 }}>
            <span style={{ marginRight: 5 }}>请输入你要搜索的物料号:</span>
            <Select
              showSearch
              style={{ width: 200 }}
              optionFilterProp="children"
              onChange={this.onChange}
              filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {children}
            </Select>
            <Button onClick={this.clickSearch} style={{ marginLeft: 10, marginRight: 10 }}>
              搜索
            </Button>
            <Button onClick={this.clickHistory}>历史数据</Button>
          </div>
          <OrderForm order={workingOrder} />
        </Card>

        <Modal
          title={'光栅被挡报警框!'}
          visible={grateHidded}
          width={window.screen.availWidth - 1000}
          closable={false}
          footer={[
            <Button type="primary" onClick={this.clear_grate_alarm}>
              解除光栅报警继续作业
            </Button>,
            <Button style={{ marginLeft: 20 }} onClick={this.clearLv1FullQuit}>
              取出收料平台1
            </Button>,
            <Button style={{ marginLeft: 20 }} onClick={this.clearLv2FullQuit}>
              取出收料平台2
            </Button>,
            <Button style={{ marginLeft: 8 }} onClick={this.clickReset} disabled={autoState}>
              复位
            </Button>,
          ]}
        >
          <div>光栅被挡,请解除光栅报警继续作业!</div>
        </Modal>

        <Modal
          title={'底层报警信息提示框'}
          visible={mainAlarmInfoVisible}
          width={window.screen.availWidth - 700}
          closable={false}
          footer={[
            <Button
              style={{ marginLeft: 8 }}
              onClick={this.clickStopProduce}
              disabled={!autoState && !mainZmcStates.run}
            >
              停止
            </Button>,
            <Button style={{ marginLeft: 8 }} onClick={this.clickReset} disabled={autoState}>
              复位
            </Button>,
          ]}
        >
          <p>{mainAlarmInfo}</p>
        </Modal>
        <Modal
          title={'复位提示框'}
          visible={resetModalVisible}
          width={window.screen.availWidth - 700}
          closable={true}
          onCancel={this.closeResetModal}
          footer={[
            <Button key="1" onClick={this.updateStartAllModal}>
              关闭复位提示框
            </Button>,
            <Button
              key="2"
              style={{ marginLeft: 8 }}
              onClick={this.clickStopProduce}
              disabled={!autoState && !mainZmcStates.run}
            >
              停止
            </Button>,
            <Button
              key="3"
              style={{ marginLeft: 8 }}
              onClick={this.clickReset}
              disabled={autoState}
            >
              复位
            </Button>,
          ]}
        >
          <p>{resetModalInfo}</p>
        </Modal>

        <Modal
          title={'作业过程中通信异常提示框'}
          visible={errorInfoModalVisble}
          width={window.screen.availWidth - 700}
          closable={true}
          onCancel={this.closeErrorInfoModal}
          footer={[
            <Button key="1" onClick={this.closeErrorInfoModal}>
              关闭提示框
            </Button>,
            <Button key="2" onClick={this.clickStopProduce} style={{ marginLeft: 15 }}>
              停止
            </Button>,
            <Button
              key="3"
              onClick={this.clickResetAll}
              style={{ marginLeft: 15 }}
              disabled={mainZmcStates.run}
            >
              总复位
            </Button>,
          ]}
        >
          <p>{errorInfo}</p>
        </Modal>

        <Modal
          title={'设备启动提示框'}
          visible={produceStartModalVisible}
          width={window.screen.availWidth - 700}
          closable={true}
          onCancel={this.closeProduceStartModal}
          footer={[
            <Button key="1" type="primary" onClick={this.closeProduceStartModal}>
              关闭启动提示框
            </Button>,
            <Button
              key="2"
              style={{ marginLeft: 15 }}
              onClick={this.clickStopProduce}
              disabled={!autoState && !mainZmcStates.run}
            >
              停止
            </Button>,

            <Button
              key="3"
              style={{ marginLeft: 15 }}
              onClick={this.clickReset}
              disabled={mainZmcStates.run}
            >
              总复位
            </Button>,
          ]}
        >
          <p>{produceStartModalInfo}</p>
        </Modal>

        <Modal
          title={'选择作业去向提示框'}
          visible={chooseToWhereModalVislbe}
          width={window.screen.availWidth - 1400}
          closable={true}
          onCancel={this.closeProduceStartModal}
          footer={[
            <Button key="1" style={{ marginLeft: 15 }} onClick={this.clickChooseToWhere}>
              确定
            </Button>,
          ]}
        >
          <Radio.Group onChange={this.onRadioChage} value={radioValue}>
            <p>
              {' '}
              <Radio value={1}>放到收料平台1</Radio>{' '}
            </p>
            <p>
              <Radio value={2}>放到收料平台2</Radio>{' '}
            </p>
            {BMSR ? (
              <Button style={{ marginLeft: 40 }} onClick={this.setAGVOrArtificial}>
                AGV模式
              </Button>
            ) : (
              <Button style={{ marginLeft: 20 }} onClick={this.setAGVOrArtificial}>
                人工模式
              </Button>
            )}
          </Radio.Group>
        </Modal>
      </>
    );
  }
}
export default Produce;
